<template>
    <a-form :form="form" style="padding: 10px;" class="editl-form">
        <a-form-item style="display: none">
            <a-input v-decorator="['id']"/>
            <a-input v-decorator="['isDialog']"/>
        </a-form-item>
        <a-collapse v-model="panelActiveKeys" expandIconPosition="right">
            <a-collapse-panel key="1" :header="i18n('list.infomation','基本信息')" class="cp-box">
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','名称')">
                          <rx-input-i18n :placeholder="i18n('form.name','名称')" @blur="getPinyinByName"
                                         v-decorator="['i18nJson', {rules: [{required: true, message: i18n('form.name','名称','input')}]}]"
                          />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.markKey','标识键')">
                            <a-input :placeholder="i18n('form.markKey','标识键')" v-decorator="['key', {rules: [
                                {required: true, message: i18n('form.markKey','标识键','input')},
                                {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:i8n2('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                                ]}]"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row v-show="mdl.isDialog!='YES' && useCondSqlType!='WEBREQ' && useCondSqlType!='INTERFACE'">
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.scheme','方案')">
                            <a-radio-group v-model="solution" @change="changeSolution">
                                <a-radio value="formSolution">{{i18n('formScheme','表单方案')}}</a-radio>
                                <a-radio value="busSolution">{{i18n('businessPlan','业务方案')}}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" class="rx-col">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.classify','分类')" >
                            <rx-category-select cat-key="FORM" :isGrant="true"
                                                v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                v-decorator="['treeId', {rules: [{required: true, message: i18n('form.classify','请选择分类','select')}]}]"></rx-category-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row v-show="mdl.isDialog!='YES' && useCondSqlType!='WEBREQ' && useCondSqlType!='INTERFACE' && solution!='busSolution'">
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.editForm','表单方案(编辑)')">
                            <rx-input-button style="width: 100%;" class="input-button-edit" @click="selectSolution2"
                                             v-decorator="['formAlias']"
                            ></rx-input-button>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.detailScheme','表单方案(明细)')">
                            <rx-input-button style="width: 100%;" class="input-button-edit" @click="selectSolution1"
                                             v-decorator="['formDetailAlias']"
                            ></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row v-show="mdl.isDialog!='YES' && useCondSqlType!='WEBREQ' && useCondSqlType!='INTERFACE'">
                    <!-- <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类">
                            <rx-category-select cat-key="FORM" :isGrant="true"
                                                v-decorator="['treeId', {rules: [{required: true, message: '请输入分类'}]}]"></rx-category-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.newForm','表单方案(新增)')" v-if="solution!='busSolution'">
                            <rx-input-button style="width: 100%;" class="input-button-edit" @click="selectSolution1"
                                             v-decorator="['formAddAlias']"
                            ></rx-input-button>
                        </a-form-item>
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('businessPlan','业务方案')" v-else >
                            <rx-input-button style="width: 100%;" class="input-button-edit" :placeholder="i18n('businessPlan','业务方案','select')" @click="setBusSolution"
                                             v-model="mdl.busSolution"></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row v-show="mdl.isDialog=='YES' || useCondSqlType=='WEBREQ' || useCondSqlType=='INTERFACE'">
                    <a-col :span="12">
                        <a-form-item  :label="i18n('form.classify','分类')" :labelCol="{span:6}" :wrapperCol="{sapn:18}" class="rx-form-item">
                            <rx-category-select cat-key="FORM" :isGrant="true" v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                v-decorator="['treeId', {rules: [{required: true, message: i18n('form.classify','请选择分类','select')}]}]"></rx-category-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  :label="i18n('form.boDef','业务模型')" :labelCol="{span:6}" :wrapperCol="{sapn:18}" class="rx-form-item">
                            <rx-input-button @click="setBoDef"  v-decorator="['boDef']" ></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="$ti18('rxForm.describe','描述')">
                            <a-textarea :placeholder="$ti18('rxForm.describe','描述')" v-decorator="['descp']" :rows="3"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
            <a-collapse-panel key="2" :header="i18n('list.paraConfig','参数配置')" class="cs-setting">
                <a-row>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.lineEdit','行编辑')">
                            <a-switch v-model="rowEdit"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.multiSelect','是否多选')">
                            <a-switch v-model="multiSelect"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.loadData','初始化加载数据')">
                            <a-switch v-model="isInitData"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.enableTree','启用导航树')">
                            <a-switch v-model="isLeftTree"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.dataType','数据展示类型')">
                            <a-radio-group :placeholder="i18n('form.dataType','数据展示类型')" v-decorator="['dataStyle']">
                                <a-radio value="list">{{i18n('form.dataList','数据列表')}}</a-radio>
                                <a-radio value="tree">{{i18n('form.treeList','树列表')}}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.lazyLoading','懒加载')">
                            <a-switch v-model="isLazy"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.debugMode','调试模式')">
                            <a-switch v-model="isTest"/>
                            <a-tooltip>
                                <span slot="title">
                                    <a href="/jpaas/sysMgr/home/SystemTools/FormSqlLogList">{{i18n('debugModeTip','开启后可前往系统管理-系统工具-公式列表日志检查是否正确')}}</a>
                                </span>
                                <a-icon style="margin-left: 5px" type="question-circle-o"/>
                            </a-tooltip>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.pageOrNot','是否分页')">
                            <a-switch v-model="isPage"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6" v-show="isPage">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.pageSize','分页大小')" >
                            <a-select v-decorator="['pageSize']">
                                <a-select-option :value="10">10</a-select-option>
                                <a-select-option :value="20">20</a-select-option>
                                <a-select-option :value="30">30</a-select-option>
                                <a-select-option :value="40">40</a-select-option>
                                <a-select-option :value="50">50</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.exportLimit','导出数量限制')">
                            <a-input-number v-model="restriction" :max="100000"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.totalLine','统计行')">
                            <a-switch v-model="showSummaryRow"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.configLine','配置展示行')">
                            <a-switch v-model="isExpandRow"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.autoHeight','高度自适应')">
                            <a-switch v-model="heightAuto"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol">
                            <span slot="label">
                                {{i18n('form.rowOverflow','行省略')}}
                                <a-tooltip>
                                    <a-tooltip>
                                        <template slot="title">
                                            {{i18n('form.rowOverflowTips','')}}
                                        </template>
                                        <a-icon type="question-circle" />
                                    </a-tooltip>
                                </a-tooltip>
                            </span>
                            <a-switch v-model="rowOverflow"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.seqColumn','序号列')">
                            <a-switch v-model="hasSeq"/>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol3" :wrapperCol="wrapperCol" :label="i18n('form.selectColumn','选择列')">
                            <a-switch v-model="hasSelect"/>
                        </a-form-item>
                    </a-col>


                </a-row>

            </a-collapse-panel>
            <a-collapse-panel key="3" :header="i18n('list.dataSource','数据来源')">
                <a-row>

                    <a-col :span="12" v-if="(useCondSqlType=='NO' || useCondSqlType=='YES') && !isTenant">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.dataSource','数据源')">
                            <rx-input-button style="width: 100%;" class="input-button-edit" @click="openDataSource"
                                             v-decorator="['dbAs']"
                            ></rx-input-button>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.SQlMode','SQL构建方式')">
                            <a-radio-group :placeholder="i18n('form.SQlMode','SQL构建方式')" v-decorator="['useCondSql']" @change="userCondSqlChange">
                                <a-radio value="NO">SQL(FreeMarker)</a-radio>
                                <a-radio value="YES">SQL(Groovy)</a-radio>
                                <a-radio value="WEBREQ">{{i18n('form.webRequest','Web请求接口')}}</a-radio>
                                <a-radio value="INTERFACE">{{i18n('form.thirdParty','第三方接口')}}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>

                    <a-col :span="12" v-show="useCondSqlType=='WEBREQ'">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.resultScript','Web请求结果集脚本')" class="labelText">
                            <rx-input-button style="width: calc(100% - 100px);float: left;" class="input-button-edit"
                                             v-decorator="['webreqKey']" @click="getWebReq"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-show="useCondSqlType=='WEBREQ'">
                        <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.script','脚本')">
                            <rx-monaco-editor
                                ref="webreqScript"
                                :key="key"
                                :placeholder="i18n('form.resultScript','Web请求结果集脚本')" v-decorator="['webreqScript']"
                                language="java"
                                style="height:300px;"
                            >
                                <template v-slot:monacoeditor>
                                    <div>
                                        <a-button style="margin-right: 8px" @click="showWebReqScriptDialog()">{{i18n('list.fastScript','快速脚本')}}</a-button>
                                    </div>
                                </template>
                            </rx-monaco-editor>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" v-show="useCondSqlType=='INTERFACE'">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                     :label="i18n('form.thirdPartySel','第三方接口选择')" class="labelText">
                            <rx-input-button style="width: calc(100% - 100px);float: left;" class="input-button-edit"
                                             v-decorator="['interfaceKey']" @click="getInterface"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item v-show="useCondSqlType=='NO'" :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                     :label="i18n('form.SQL','SQL语句') + '(Freemarker)'" class="labelText">

                            <rx-monaco-editor
                                ref="sql"
                                :key="key"
                                v-decorator="['sql', {rules: [{required: false, message: $ti18('rxDecorator.input','请输入') + 'SQL'}]}]"
                                language="sql"
                                style="height:300px;"
                            >
                                <template v-slot:monacoeditor>
                                    <div>
                                        <a-dropdown>
                                            <a-menu slot="overlay" @click="onSqlExp($event,'sql')">
                                                <a-menu-item key="{CREATE_BY_}">{{i18n('currUser','当前用户')}}ID</a-menu-item>
                                                <a-menu-item key="{DEP_ID_}">{{i18n('currDepart','当前部门')}}ID</a-menu-item>
                                                <a-menu-item key="{TENANT_ID_}">{{i18n('currOrgan','当前机构')}}ID</a-menu-item>
                                                <a-menu-item key="{COMPANY_ID_}">{{i18n('currCompany','当前公司')}}ID</a-menu-item>
                                                <a-menu-item key="{menuId}">{{i18n('currMenu','当前菜单')}}ID</a-menu-item>
                                            </a-menu>
                                            <a-button style="margin-right: 8px">{{i18n('insertSQL','插入上下文的SQL条件参数')}}
                                                <a-icon type="down"/>
                                            </a-button>
                                        </a-dropdown>
                                        <a-dropdown >
                                            <a-menu slot="overlay"  >
                                                <template v-for="item in constantField">
                                                    <a-menu-item :key="item.value"
                                                                 @click="sqlInsertChange(item.value,'sql')"
                                                                 v-if="!item.children"> {{item.label}}
                                                    </a-menu-item>
                                                </template>
                                            </a-menu>
                                            <a-button style="margin-right: 8px">{{i18n('form.insertConstant','插入常量')}}
                                                <a-icon type="down"/>
                                            </a-button>
                                        </a-dropdown>
                                        <a-button style="margin-right: 8px" @click="insertExp('/*TABLE*/','sql')">{{i18n('list.tableForm','表单占位符')}}</a-button>
                                        <a-button style="margin-right: 8px" @click="insertExp('/*CONDITION*/','sql')">{{i18n('list.condition','条件占位符')}}</a-button>
                                        <a-button style="margin-right: 8px" @click="insertExp('/*ORDERBY*/','sql')">{{i18n('list.sortPlace','排序占位符')}}</a-button>
                                    </div>
                                </template>
                            </rx-monaco-editor>
                        </a-form-item>
                        <a-form-item v-show="useCondSqlType=='YES'" :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                     :label="i18n('list.buildSQL','构建SQL(Groovy)语句')">
                            <rx-monaco-editor
                                ref="condSqls"
                                :key="key"
                                v-decorator="['condSqls', {rules: [{required: false, message: $ti18('rxDecorator.input','请输入') + 'SQL'}]}]"
                                language="java"
                                style="height:300px;"
                            >
                                <template v-slot:monacoeditor>
                                    <div>
                                      <a-button style="margin-right: 8px" @click="showScriptDialog()">{{i18n('list.fastScript','快速脚本')}}</a-button>
                                      <a-dropdown>
                                        <a-menu slot="overlay" @click="onSqlExp($event,'condSqls')">
                                          <a-menu-item key="{CREATE_BY_}">{{i18n('currUser','当前用户')}}ID</a-menu-item>
                                          <a-menu-item key="{DEP_ID_}">{{i18n('currDepart','当前部门')}}ID</a-menu-item>
                                          <a-menu-item key="{TENANT_ID_}">{{i18n('currOrgan','当前机构')}}ID</a-menu-item>
                                          <a-menu-item key="{COMPANY_ID_}">{{i18n('currCompany','当前公司')}}ID</a-menu-item>
                                          <a-menu-item key="{menuId}">{{i18n('currMenu','当前菜单')}}ID</a-menu-item>
                                        </a-menu>
                                        <a-button style="margin-right: 8px">{{i18n('insertSQL','插入上下文的SQL条件参数')}}
                                          <a-icon type="down"/>
                                        </a-button>
                                      </a-dropdown>
                                      <a-dropdown >
                                        <a-menu slot="overlay"  >
                                          <template v-for="item in constantField">
                                            <a-menu-item :key="item.value"
                                                         @click="sqlInsertChange(item.value,'condSqls')"
                                                         v-if="!item.children"> {{item.label}}
                                            </a-menu-item>
                                          </template>
                                        </a-menu>
                                        <a-button style="margin-right: 8px">{{i18n('form.insertConstant','插入常量')}}
                                          <a-icon type="down"/>
                                        </a-button>
                                      </a-dropdown>
                                      <a-button style="margin-right: 8px" @click="insertExp('/*TABLE*/','condSqls')">{{i18n('list.tableForm','表单占位符')}}</a-button>
                                      <a-button style="margin-right: 8px" @click="insertExp('/*CONDITION*/','condSqls')">{{i18n('list.condition','条件占位符')}}</a-button>
                                      <a-button style="margin-right: 8px" @click="insertExp('/*ORDERBY*/','condSqls')">{{i18n('list.sortPlace','排序占位符')}}</a-button>
                                      <a target="_blank" href="https://alidocs.dingtalk.com/i/p/Dnb9XJlQxLaGyAp7pLmkQxNgpMV9Qz2g">
                                         <a-icon type="question-circle" />
                                      </a>
                                    </div>
                                </template>
                            </rx-monaco-editor>
                        </a-form-item>

                    </a-col>
                </a-row>

            </a-collapse-panel>
            <a-collapse-panel key="4" :header="i18n('form.basicStyle','基础风格')">
                <a-row >
                    <a-col :span="6" v-show="mdl.isDialog=='YES'">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.listSize','弹窗大小')">
                            <a-radio-group :placeholder="i18n('form.listSize','列表大小')" v-decorator="['isMax',{initialValue:'YES'}]" @change="isMaxChange">
                                <a-radio value="YES">{{i18n('form.fullScreen','全屏')}}</a-radio>
                                <a-radio value="NO">{{i18n('form.customSize','自定义大小')}}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.masks','是否显示遮罩')">
                            <a-radio-group :placeholder="i18n('form.masks','是否显示遮罩')" v-decorator="['isShade',{initialValue:'YES'}]">
                                <a-radio value="YES">{{i18n('yes','是')}}</a-radio>
                                <a-radio value="NO">{{i18n('no','否')}}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.rowHeight','行高')" class="line-height">
                        <a-select v-decorator="['lineHeight']">
                          <a-select-option :value="30">30</a-select-option>
                          <a-select-option :value="40">40</a-select-option>
                          <a-select-option :value="50">50</a-select-option>
                        </a-select>
                        <span class="mlf">px</span>
                      </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item>
                            <span slot="label">
                                {{i18n('selectList','已选列表')}}
                                <a-tooltip>
                                    <template slot="title">
                                         {{i18n('selectListData','右侧显示已选中的数据')}}
                                    </template>
                                    <a-icon type="question-circle" />
                                </a-tooltip>
                            </span>
                            <a-switch v-model="selectList"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row v-show="mdl.isDialog=='YES' && mdl.isMax=='NO'">
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol2" :wrapperCol="wrapperCol" :label="i18n('form.height','高度')">
                            <a-input-number style="width:620px;" :placeholder="i18n('form.height','高度')" v-decorator="['height']" :min="100"
                                            :max="1500"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.width','宽度')">
                            <a-input-number style="width:620px;" :placeholder="i18n('form.width','宽度')" v-decorator="['width']" :min="100"
                                            :max="1500"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <span class="bgfg-text">{{i18n('form.tableStyle','表格风格')}}:</span>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item :labelCol="labelCol2" style="margin-left: 23px;">
                            <a-radio-group :placeholder="i18n('form.tableStyle','表格风格')" v-decorator="['tableStyle']">
                                <a-radio :value="1">
                                    <list-style-table :border="true"></list-style-table>
                                </a-radio>
                                <a-radio :value="2">
                                    <list-style-table :color="true"></list-style-table>
                                </a-radio>
                                <a-radio :value="3">
                                    <list-style-table></list-style-table>
                                </a-radio>
                                <a-radio :value="4">
                                    <list-style-table :border="true" :color="true"></list-style-table>
                                </a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-collapse-panel>
        </a-collapse>


    </a-form>
</template>
<script>
    import FormBoListApi from '@/api/form/core/formBoList'
    import FormSolutionApi from '@/api/form/core/formSolution'
    import SysWebReqDefApi from "@/api/system/core/sysWebReqDef"
    import {BaseForm, Dialog, RxInputButton, RxMonacoEditor, Util,JsConstant} from "@lowcode/jpaas-common-lib";
    import DialogBox from "../../../../assets/js/DialogBox";
    import FormBoEntityApi from "../../../../api/form/bo/formBoEntity";
    import listStyleTable from "@/views/modules/form/core/listCommon/listStyleTable";
    import FormCustomQueryApi from "@/api/form/core/formCustomQuery";
    import FormBoDefApi from "@/api/form/bo/formBoDef";
    import AppName from "@/assets/js/AppName.js";
    export default {
        name: 'FormBoListEdit1',
        props: ["isDialog","curAppObj","otherAppId","appDsAlias"],
        mixins: [BaseForm,AppName],
        components: {
            RxInputButton,
            RxMonacoEditor,
            listStyleTable
        },
        data() {
            return {
                labelCol2: { span:3 },
                labelCol3: { span:8 },
                wrapperCol1: { span:19 },
                useCondSqlType: "NO",
                panelActiveKeys:['1','2','3','4'],
                isTestOptions: [
                    {label: this.i18n('yes','是'), value: 'YES'},
                    {label: this.i18n('no','否'), value: 'NO'}
                ],
                complexJson: {
                    main: {
                        formAlias: {text: "formName", value: "formAlias"},
                        formDetailAlias: {text: "formDetailName", value: "formDetailAlias"},
                        formAddAlias: {text: "formAddName", value: "formAddAlias"},
                        webreqKey: {text: "webreqName", value: "webreqKey"},
                        interfaceKey: {text: "interfaceName", value: "interfaceKey"},
                        dbAs: {text: "dbAs", value: "dbAs"}
                    }
                },
                solution:"formSolution",
                isTenant:false,
                //isSearchHeader:false,
                rowEdit:false,
                multiSelect:true,
                isLeftTree:false,
                isPage:true,
                rowOverflow:true,
                hasSeq:true,
                hasSelect:true,
                selectList:false,
                isInitData:true,
                isLazy:false,
                isTest:false,

                isExpandRow:false,
                showSummaryRow:false,
                heightAuto:false,

                restriction:1000,
                constantField: [],
                key:Util.randomId()
            }
        },
        created() {
            this.isUserManager(this.$route.query.appId);
            this.loadConstants();
        },
        mounted(){
            let self = this;
                setTimeout(function () {
                    self.key=Util.randomId();
                    if(self.appDsAlias && !self.pkId){
                        self.form.setFieldsValue({dbAs:JSON.stringify({text:self.appDsAlias,value:self.appDsAlias})});
                    }
                },100)
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "formBoListDialog", key);
            },
            i8n2(name, text, key){
                return this.$ti18(name,text,"formBoEntity",key);
            },
            obtainName(){
                let i18nJson=this.form.getFieldsValue().i18nJson;
                this.$emit('initName',this.$i18(i18nJson))
            },
            getPinyinByName(){
                this.obtainName()
                let i18nJson=this.form.getFieldsValue().i18nJson;
                this.$emit('initName',this.$i18(i18nJson))
                if (!this.$i18(i18nJson)){
                    return;
                }
                if (this.form&&this.form.getFieldsValue().key){
                    return;
                }
                this.getPinyin(this.$i18(i18nJson)).then(res => {
                    //去除不可见的特殊符号
                    if(res){
                        res=res.replace(/\u200B/g,'');
                    }
                    this.form.setFieldsValue({key:res})
                })
            },
            selectSolution(vm, callback) {
                var config = {curVm: this, widthHeight: ['900px', '700px'], data: {multiSelect: false}};
                DialogBox.openSoution(config, function (data) {
                    vm.setVal(data.alias, data.name)
                    if (callback) {
                        callback(data);
                    }
                })
            },
            //获取常量字段
            loadConstants() {
                FormCustomQueryApi.getConstants().then(data => {
                    this.constantField = this.constantField.concat(data.map(item => {
                        return {label: item.val, value: item.key}
                    }));
                })
            },
            //点击某个常量触发
            sqlInsertChange(value,type) {
                this.$refs[type].insertContent(value);
                this.sqlShow = "";
            },
            selectSolution1(vm) {
                this.selectSolution(vm);
            },
            selectSolution2(vm) {
                var self = this;
                this.selectSolution(vm, function (data) {
                    //已经存在值时，不需要再复制值
                    if(!self.form.getFieldValue('name')
                        &&  !self.form.getFieldValue('key')){
                        var mdl = Object.assign(self.form.getFieldsValue(), {
                            i18nJson: data.name + self.i18n('List','列表'),
                            key: data.alias + '_list'
                        });
                        self.form.setFieldsValue(mdl);
                    }

                    if (data.bodefId) {
                        FormBoEntityApi.getMainExcludeAttrsByBoDefId(data.bodefId).then(res => {
                            if (res.data) {
                                if (self.useCondSqlType == 'NO' && !self.form.getFieldValue('sql')) {
                                    var str = 'select * from ' + res.data.tableName;
                                    self.$refs.sql.insertContent(str);
                                } else if (self.useCondSqlType == 'YES' && !self.form.getFieldValue('condSqls')) {
                                    var str = 'String sql = "select * from ' + res.data.tableName + '";\n' +
                                        'return sql;';
                                    self.$refs.condSqls.insertContent(str);
                                }
                                self.form.setFieldsValue({dbAs:JSON.stringify({text:res.data.dsName,value:res.data.dsAlias})});
                                self.obtainName()
                            }
                        })
                    }
                });
            },
            get(id) {
                return FormBoListApi.get(id);
            },
            save(values) {
                let appId=this.curAppObj.appId;
                if(appId && !this.pkId){
                    values.appId=appId;
                }
                //values.isSearchHeader=this.isSearchHeader?'YES':'NO';
                values.rowEdit=this.rowEdit?'YES':'NO';
                values.multiSelect=this.multiSelect?'YES':'NO';
                values.isLeftTree=this.isLeftTree?'YES':'NO';
                values.isPage=this.isPage?'YES':'NO';

                values.isInitData=this.isInitData?'YES':'NO';
                values.isLazy=this.isLazy?'YES':'NO';
                values.isTest=this.isTest?'YES':'NO';

                values.isExpandRow=this.isExpandRow?'YES':'NO';
                values.heightAuto=this.heightAuto?'YES':'NO';
                values.showSummaryRow=this.showSummaryRow?'YES':'NO';

                values.rowOverflow=this.rowOverflow;
                values.hasSeq = this.hasSeq
                values.hasSelect = this.hasSelect
                values.restriction=this.restriction?this.restriction:-1;
                values.fontPosition=values.fontPosition || "left";
                values.selectList = this.selectList

                return FormBoListApi.save(values);
            },
            handleSubmit(self, this_) {
                this_.form.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    if(!Util.hasChineseAndSpecialChars(values.key)){
                        this_.$message.warning('标识中不能包含中文以及特殊字符~');
                        return;
                    }
                    values.pkId = this_.pkId;
                    values.appId=this_.curAppObj.appId;
                    if(this_.otherAppId){
                        values.appId=this_.otherAppId;
                    }

                    this_.confirmLoading = true;
                    if (this_.validForm) {
                        var flag = this_.validForm(values);
                        if (!flag) {
                            return;
                        }
                    }
                    this_.onSubmit(values);

                    if (!values.formAlias) {
                        values.formName = "";
                    }
                    if (!values.formAddAlias) {
                        values.formAddName = "";
                    }
                    if (!values.formDetailAlias) {
                        values.formDetailName = "";
                    }
                    if(!values.interfaceKey){
                        values.interfaceName = "";
                    }
                    if(!values.busSolution){
                        values.busSolution =this_.mdl.busSolution?this_.mdl.busSolution: "";
                    }
                    if(this.isTenant){
                        values.isTenant="1";
                        values.dbAs="";
                    }else {
                        values.isTenant="0";
                    }
                    // 如果已经保存过，或者不是数据列表，不生成默认按钮
                    if (values.pkId || values.isDialog == 'YES'){
                        self.initButtons = []
                    }else {
                        let key = values.key
                        self.initButtons = self.initButtons.map(button => {
                            button.btnName = key + button.btnName
                            return button
                        })
                    }
                    this_.save(values).then(res => {
                        if (res.success && res.code == 200) {
                            self.newPkId = res.data.pkId;
                            self.currentView = self.edit2;
                            self.currentName = "edit2";
                            self.oktext = self.$ti18('rxForm.saveBtn','保存');
                            /*触发更新在表单设计的弹窗刷新*/
                            self.$broadCast && self.$broadCast.postMessage('formDesign')
                        }
                    }).catch(() => {
                        this_.$message.error(self.$ti18('rxMsa.sysError','系统错误，请稍后再试!'))
                    }).finally(() => {
                        this_.confirmLoading = false
                    })
                })
            },
            onload_(values) {
                //默认值
                var data = {
                    treeId:this.$route.query.treeId?this.$route.query.treeId:'',//添加分类
                    isDialog: this.isDialog,
                    height: 480,
                    width: 780,
                    isMax:this.isDialog=='NO'?"YES":"NO",
                    isShade:"YES",
                    multiSelect: 'true',
                    isPage: 'YES',
                    pageSize: 20,
                    isLeftTree: 'NO',
                    dataStyle: 'list',
                    useCondSql: 'NO',

                    isLazy: 'NO',
                    isTest: 'NO',

                    isSearchHeader: 'YES',
                    isInitData: 'YES',

                    isExpandRow: 'NO',
                    heightAuto: 'NO',
                    isCheckboxProps: 'NO',

                    busSolution:'',
                    fontPosition:'left',
                    lineHeight:40,
                    tableStyle:1,
                    boDef:"",
                    rowOverflow:true
                };
                if (values) {

                    //this.isSearchHeader = values.isSearchHeader=='YES'?true:false;
                    this.rowEdit = values.rowEdit=='YES'?true:false;
                    this.multiSelect = values.multiSelect=='YES'?true:false;
                    this.isLeftTree = values.isLeftTree=='YES'?true:false;
                    this.isPage = values.isPage=='YES'?true:false;

                    this.isInitData = values.isInitData=='YES'?true:false;
                    this.isLazy = values.isLazy=='YES'?true:false;
                    this.isTest = values.isTest=='YES'?true:false;

                    this.isExpandRow = values.isExpandRow=='YES'?true:false;
                    this.heightAuto = values.heightAuto=='YES'?true:false;
                    this.showSummaryRow = values.showSummaryRow=='YES'?true:false;
                    this.rowOverflow = values.rowOverflow?true:false;
                    this.hasSelect = values.hasSelect
                    this.selectList = values.selectList
                    this.hasSeq = values.hasSeq

                    this.restriction = values.restriction?values.restriction:-1;

                    this.useCondSqlType = values.useCondSql;
                    values.condSqls = values.condSqls ? values.condSqls : "";
                    if( values.busSolution){
                        data.busSolution =values.busSolution;
                        this.solution="busSolution";
                    }
                    this.isTenant=values.isTenant=="1"?true:false;
                }
                this.mdl = Object.assign(data);
                this.form.setFieldsValue(this.mdl)
            },

            openDataSource(vm) {

                Dialog.openDataSourceDialog({
                    curVm: this, widthHeight: ['1200px', '600px'],
                    data: {appName: this.serviceName}
                }, function (self, data) {
                    vm.setVal(data.alias, data.name);
                })
            },
            isMaxChange(e){
                this.mdl.isMax = e.target.value;
            },
            userCondSqlChange(e) {
                this.key=Util.randomId();
                this.useCondSqlType = e.target.value;
                this.mdl.useCondSql = e.target.value;
            },
            onSqlExp(e,type) {
                this.$refs[type].insertContent("$" + e.key);
            },
            insertExp(text,type) {
                this.$refs[type].insertContent(text);
            },
            getWebReq(vm) {
                let self_ = this;
                Dialog.openSysWebReqDialog({
                    curVm: this, widthHeight: ['1300px', '600px']
                }, function (self, data) {
                    vm.setVal(data.alias,data.name);
                    var webreqScript = self_.form.getFieldValue("webreqScript");
                    if (!webreqScript) {
                        SysWebReqDefApi.initDefaultCode({alias: data.alias}).then(res => {
                            if (res.success) {
                                var resJson = res.data;
                                self_.$refs.webreqScript.insertContent(resJson.resultHeaderCode);
                            }
                        })
                    }
                })
            },
            validInterfaceReturn(fieldsStr){
                if (fieldsStr && fieldsStr!='[]') {
                    var fields = JSON.parse(fieldsStr);
                    if(fields[0].paramType=='object' &&
                        fields[0].children &&
                        fields[0].children.length>0 &&
                        fields[0].children[0].paramType=='array' &&
                        fields[0].children[0].paramName=='result' &&
                        fields[0].children[0].children &&
                        fields[0].children[0].children.length>0 &&
                        fields[0].children[0].children[0].children &&
                        fields[0].children[0].children[0].children.length>0){
                        return true;
                    }
                }
                this.$message.error(this.i18n('notSupport','不支持此返回结果结构的接口！'));
                return false;
            },
            getInterface(vm){
                Dialog.openSysInterfaceDialog({
                    curVm: this,max:true,
                }, function (self, data) {
                    var fieldStr = data.apiReturnFields;
                    if(!self.validInterfaceReturn(fieldStr)){
                        return;
                    }
                    vm.setVal(data.apiKey,data.apiName);
                })
            },
            changeSolution(e){
                if(e.target.value!='busSolution'){
                    this.mdl.busSolution="";
                }
            },
            setBusSolution(vm){
                var self=this;
                var config = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
                DialogBox.openBusSolutionDialog(config, function (data) {
                    vm.setVal(data.alias, data.name);
                    var mdl = Object.assign(self.form.getFieldsValue(), {
                        i18nJson: data.name + self.i18n('List','列表'),
                        key: data.alias + '_list',
                    });
                    self.form.setFieldsValue(mdl);
                    if(data.mainFormSolution){
                        var mainFormSolution=JSON.parse(data.mainFormSolution);
                        FormSolutionApi.getBoEntityBySolAlias(mainFormSolution.value).then(res=>{
                            if (res.data) {
                                if (self.useCondSqlType == 'NO' && !self.form.getFieldValue('sql')) {
                                    var str = 'select * from ' + res.data.tableName;
                                    self.$refs.sql.insertContent(str);
                                } else if (self.useCondSqlType == 'YES' && !self.form.getFieldValue('condSqls')) {
                                    var str = 'String sql = "select * from ' + res.data.tableName + '";\n' +
                                        'return sql;';
                                    self.$refs.condSqls.insertContent(str);
                                }
                                self.form.setFieldsValue({dbAs:JSON.stringify({text:res.data.dsName,value:res.data.dsAlias})});
                                self.obtainName()
                            }
                        });
                    }
                })
            },
            showScriptDialog(){
                let self=this;
                let config={curVm:this};
                Dialog.openScriptDialog(config,function (script){
                    self.$refs.condSqls.insertContent(script);
                })
            },
            showWebReqScriptDialog(){
                let self=this;
                let config={curVm:this};
                Dialog.openScriptDialog(config,function (script){
                    self.$refs.webreqScript.insertContent(script);
                })
            },
            setBoDef(vm){
                let self_ = this;
                Dialog.openBoDefDialog({
                    curVm: this, widthHeight: ['1000px', '600px'], data: {supportDb: true}
                }, function (data) {
                    if(data){
                        vm.setVal(data.id, data.name);
                        self_.form.setFieldsValue({boDef:JSON.stringify({text:data.name,value:data.id})});
                        if (self_.useCondSqlType == 'NO' && !self_.form.getFieldValue('sql')) {
                            self_.insertSqlByDef(data.id);
                        }
                    }
                })
            },
            /**
             * 根据模型Id插入sql
             * @param defId 模型Id
             */
            insertSqlByDef(defId){
                FormBoDefApi.getBoDef(defId).then(res=>{
                    if(res.success && res.data && res.data.formBoEntity){
                        let tableName = res.data.formBoEntity.tableName;
                        this.$refs['sql'].insertContent("select * from "+tableName);
                        this.form.setFieldsValue({dbAs:JSON.stringify({text:res.data.formBoEntity.dsName,value:res.data.formBoEntity.dsAlias})});
                    }
                });
            },
        }
    }
</script>
<style scoped>
.rx-form-item{
    display: flex;
}
.rx-form-item >>> .ant-form-item-control-wrapper{
    flex: 1;
}
.labelText >>> .ant-form-item-label {
    padding-right: 4px;
    white-space: normal !important;

}

.input-button-edit {
    margin-top: 6px;
}
.cp-box >>> .ant-collapse-content{
    overflow: visible;
}
.line-height >>> .ant-select{
    width: 80px;
}
.mlf{
    margin-left: 10px;
    display: inline-block;
}
.bgfg-text{
    margin-left: 23px;
    margin-bottom: 20px;
    display: inline-block;
}
.editl-form >>> .ant-form-item{
    margin-bottom: 6px;
}
.editl-form >>> .ant-form-item .ant-switch {
    height: 18px;
    min-width: 40px;
}
.editl-form >>> .ant-switch::after{
    width: 14px;
    height: 14px;
}
.editl-form .cs-setting >>> .ant-form-item{
    height: 30px;
    display: flex;
}

.editl-form .cs-setting >>> .ant-form-item-control{
    width: 180px;
}
.editl-form .cs-setting >>> .ant-form-item-control,
.editl-form .cs-setting >>> .ant-form-item-label{
    line-height: 30px;
}
</style>
